<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <!-- DPR==1 -->
  <!-- <meta name="viewport" content="width=device-width, initial-scale=1.0"> -->
  <!-- DPR==2 -->
  <meta name="viewport"
    content="width=device-width, initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5, user-scalable=no ">
  <title>通用适配方案的实现</title>
  <style>
    * {
      box-sizing: border-box;
      padding: 0;
      margin: 0;
    }

    .header-container {
      width: 100%;
      height: 2.5rem;
      background-color: red;
      border-bottom: 1px solid #000;
    }
  </style>
  <script>
    (function () {
      "use strict";
      // dpr > scale = 1/dpr
      const docEL = document.documentElement;
      // 设备宽限定
      const maxWidth = 540
      const minWidth = 320

      // h获取viewport标签
      const viewportEL = document.querySelector('meta[name="viewport"]')
      // 获取设备像素比
      let dpr = window.devicePixelRatio || 1
      // 处理DPR
      dpr = dpr >= 3 ? 3 : (dpr >= 2 ? 2 : 1)

      docEL.setAttribute('data-dpr', dpr)
      docEL.setAttribute('max-width', maxWidth)
      docEL.setAttribute('min-width', minWidth)

      const scale = 1 / dpr

      const content = `width=device-width, initial-scale= ${scale}, maximum-scale=${scale}, minimum-scale=${scale}, user-scalable=no`

      if (viewportEL) {
        viewportEL.setAttribute('content', content)
      } else {
        viewportEL = document.createElement('meta')
        viewportEL.setAttribute('name', 'viewport')
        viewportEL.setAttribute('content', content)
        document.head.appendChild(viewportEL)
      }
      setRemUnit();
      window.addEventListener("resize", setRemUnit);
      function setRemUnit() {
        var ratio = 18.75;
        var viewWidth = docEL.getBoundingClientRect().width || window.innerHeight;
        if (maxWidth && viewWidth / dpr > maxWidth) {
          viewWidth = maxWidth * dpr
        } else if (minWidth && viewWidth / dpr < minWidth) {
          viewWidth = minWidth * dpr
        }
        docEL.style.fontSize = viewWidth / ratio + "px";
      }
    })();

  </script>
</head>

<body>
  <div class="header-container"></div>
</body>

</html>